import React, {Component} from 'react';
import {StyleSheet, View, Text, FlatList, RefreshControl, ActivityIndicator, DeviceInfo} from 'react-native';
import {createAppContainer, createMaterialTopTabNavigator} from 'react-navigation';
import {connect} from 'react-redux';
import actions from '../action';
import PopularItem from '../common/PopularItem';
import NavigationBar from '../common/NavigationBar';

const URL = 'https://api.github.com/search/repositories?q=';
const QUERY_STR = '&sort=stars';
const THEME_COLOR = '#678';
const PAGE_SIZE = 10;

export default class PopularPage extends Component {
  constructor(props) {
    super(props);
    this.tabNames = ['Java', 'Android', 'IOS', 'React', 'React Native', 'JavaScript'];
    console.log('--------DeviceInfo----------', DeviceInfo);
  }

  /**
   * 生成tab内容页
   * @private
   */
  _genTabs() {
    const tabs = {};
    this.tabNames.forEach((item, index) => {
      tabs[`tab${index}`] = {
        screen: props => <PopularTabPage {...props} tabLabel={item} />, // screen可以使用函数定义，并将路由对应的props传递给要显示的组件，同理也可以传递自定义属性(例如tabLabel)
        navigationOptions: {
          tabBarLabel: item
        }
      }
    });
    return tabs;
  }

  /**
   * 生成顶部tab
   * @returns {"react-navigation".NavigationContainer}
   * @private
   */
  _topNavigator() {
    return createAppContainer(
      createMaterialTopTabNavigator(
        this._genTabs(), {
          tabBarOptions: {
            scrollEnabled: true, // 开启滚动(在Android下，初次加载会有高度闪烁的情况，需要样式控制)
            upperCaseLabel: false, // 关闭大写
            style: { // tabBar样式
              backgroundColor: THEME_COLOR,
              height: 30
            },
            tabStyle: styles.tabStyle,
            indicatorStyle: styles.indicatorStyle, // 指示器样式
            labelStyle: styles.labelStyle
          }
        }
      )
    )
  }

  /**
   * 渲染
   * @returns {*}
   */
  render() {
    const statusBar = {
      backgroundColor: THEME_COLOR,
      barStyle: 'light-content'
    };
    const Top = this._topNavigator();
    return (
      <View style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0 }}>
        <NavigationBar
          title={'最热'}
          statusBar={statusBar}
          style={{
            backgroundColor: THEME_COLOR
          }}
        />
        <Top/>
      </View>
    )
  }
}

/**
 * 顶部tab对应的下方内容组件
 */
class PopularTab extends Component {
  constructor(props) {
    super(props);
    const {tabLabel} = this.props; // 使用props接收自定义属性
    this.storeName = tabLabel
  }

  componentDidMount() {
    this.loadData();
  }
  /**
   * 发送action，加载数据
   */
  loadData(loadMore = false) {
    const {onRefreshPopular, onLoadMorePopular} = this.props;
    const store = this._store();
    const url = this.genFetchUrl(this.storeName);
    if (loadMore) {
      onLoadMorePopular(this.storeName, store.pageIndex + 1, PAGE_SIZE, store.allItems, (msg) => {
        console.log(msg);
      })
    } else {
      onRefreshPopular(this.storeName, url, PAGE_SIZE)
    }
  }

  /**
   * 获取页面相关数据
   * @returns {*}
   * @private
   */
  _store() {
    const {popular} = this.props;
    let store = popular[this.storeName];
    if (!store) { // 如果数据不存在，初始化数据
      store = {
        pageIndex: 1,
        items: [],
        allItems: [],
        isLoading: false,
        hideLoadMore: true
      }
    }
    return store;
  }
  /**
   * 生成URL
   * @param key
   * @returns {string}
   */
  genFetchUrl(key) {
    return URL + key + QUERY_STR;
  }
  /**
   * 生成FlatList的item组件
   * @param data
   * @returns {*}
   */
  renderItem(data) {
    // console.log('renderItem:', data);
    return <PopularItem
      item={data.item}
      onSelect={() => {

      }}
    />
  }

  /**
   * 生成列表底部组件
   */
  genIndicator() {
    return this._store().hideLoadMore ? null :
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
        />
        <Text>正在加载更多</Text>
      </View>
  }

  render() {
    let store = this._store();
    return (
      <View style={styles.container}>
        <FlatList
          data={store.items}
          renderItem={data=>this.renderItem(data)} // data中包含index, item等属性，item为实际数据
          keyExtractor={item => { // item为实际数据
            // console.log('keyExtractor:', item);
            return '' + item.id
          }}
          refreshControl={ // 添加下拉刷新组件
            <RefreshControl
              title={'加载中...'}
              titleColor={THEME_COLOR}
              colors={[THEME_COLOR]}
              refreshing={store.isLoading} // 是否显示
              onRefresh={() => this.loadData()} // 下拉时执行数据加载
              tintColor={THEME_COLOR}
            />
          }
          ListFooterComponent={() => this.genIndicator()}
          onMomentumScrollBegin={() => { // 滚动开始时，早于onEndReached触发
            this.canLoadMore = true;
          }}
          onEndReached={() => { // onEndReached在滚动到底部时经常会连续执行两次，所以结合onMomentumScrollBegin，保证其只执行一次
            setTimeout(() => {
              if (this.canLoadMore) {
                // console.log('----loadData(true)----');
                this.loadData(true);
                this.canLoadMore = false;
              }
            }, 100);
          }}
          onEndReachedThreshold={0.5}
        />
      </View>
    )
  }
}

/**
 * 映射state
 * @param state
 * @returns {{popular: popularReducer}}
 */
const mapStateToProps = state => ({
  popular: state.popular
});
/**
 * 映射dispatch
 * @param dispatch
 * @returns {{onLoadPopularData: function(*=, *=): *}}
 */
const mapDispatchToProps = dispatch => ({
  onRefreshPopular: (storeName, url, pageSize) => dispatch(actions.onRefreshPopular(storeName, url, pageSize)),
  onLoadMorePopular: (storeName, pageIndex, pageSize, allItems, callBack) => dispatch(actions.onLoadMorePopular(storeName, pageIndex, pageSize, allItems, callBack))
});
/**
 * 连接 PopularTab组件 与 Redux Store，返回一个处理后的PopularTabPage组件
 */
const PopularTabPage = connect(mapStateToProps, mapDispatchToProps)(PopularTab);

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  tabStyle: {
    // minWidth: 50 // 设置minWidth会使tabBar在Android环境下初次加载时闪烁
    padding: 0
  },
  indicatorStyle: {
    height: 2,
    backgroundColor: 'white'
  },
  labelStyle: {
    fontSize: 13,
    margin: 0
  },
  indicatorContainer: {
    alignItems: 'center'
  },
  indicator: {
    color: 'red',
    margin: 10
  }
});
